package com.vim.modules.web.service;

import com.vim.common.utils.IdGen;
import com.vim.common.base.CrudServiceImpl;
import com.vim.common.utils.NumberTool;
import com.vim.modules.web.model.*;
import com.vim.modules.web.dao.ShopOrderMapper;
import com.vim.modules.web.model.api.ShopOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShopOrderService extends CrudServiceImpl<ShopOrder> {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private ShopUserAddressService shopUserAddressService;

    @Resource
    private ShopCartService shopCartService;

    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;

    @Resource
    private ShopGoodsService shopGoodsService;

    @Resource
    private ShopAreaService shopAreaService;

    @Autowired
    public ShopOrderService(ShopOrderMapper mapper) {
        super(mapper);
    }

    @Override
    public int save(ShopOrder entity) {
        entity.setOrderId(IdGen.uuid());
        return super.save(entity);
    }

    /**
     * 预下单
     * @param userId        用户ID
     * @param cartIds       购物车ID列表
     * @param addressId     地址ID
     */
    public ShopOrderVo preOrder(String userId, String cartIds, String addressId) {
        return countOrder(userId, cartIds, addressId);
    }

    /**
     * 下单
     * @param userId        用户ID
     * @param cartIds       购物车ID列表
     * @param addressId     地址ID
     */
    @Transactional(rollbackFor = Exception.class)
    public ShopOrder createOrder(String userId, String cartIds, String addressId) {
        ShopOrderVo vo = countOrder(userId, cartIds, addressId);
        ShopOrder order = new ShopOrder();
        //1.订单编号
        String orderSn = "001";
        order.setOrderSn(orderSn);
        //2.买家信息
        UserInfo userInfo = userInfoService.find(userId);
        ShopUserAddress address = vo.getAddress();
        order.setBuyerId(userInfo.getUserId());
        order.setBuyerName(userInfo.getUserName());
        order.setOrderPhone(address.getBuyerPhone());
        order.setOrderAddress(shopAreaService.areaInfo(address.getDeliveryAreaId())+address.getDeliveryStreet());
        //3.订单金额
        order.setOrderTotalPrice(new BigDecimal(vo.getGoodsTotalPrice()));
        order.setOrderFreightPrice(new BigDecimal(vo.getOrderFreightPrice()));
        order.setOrderPayPrice(new BigDecimal(vo.getOrderTotalPrice()));
        //4.其余信息
        order.setCreateTime(new Date());
        save(order);
        //5.订单子表
        List<ShopCart> list = vo.getCartList();
        for(ShopCart cart:list){
            //删除对应购物车商品信息
            shopCartService.delete(cart.getCartId());
            //保存订单子表信息
            ShopOrderGoods orderGoods = new ShopOrderGoods();
            orderGoods.setOrderId(order.getOrderId());
            orderGoods.setOrderSn(order.getOrderSn());
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setGoodsPrice(cart.getGoodsPrice());
            orderGoods.setGoodsPayPrice(cart.getGoodsPrice());
            orderGoods.setGoodsNum(cart.getGoodsNum());
            orderGoods.setGoodsImage(cart.getGoodsImage());
            shopOrderGoodsService.save(orderGoods);
        }
        return order;
    }

    private ShopOrderVo countOrder(String userId, String cartIds, String addressId){
        ShopOrderVo vo = new ShopOrderVo();
        BigDecimal goodsTotalPrice = BigDecimal.ZERO;
        BigDecimal orderFreightPrice = BigDecimal.ZERO;
        BigDecimal orderTotalPrice = BigDecimal.ZERO;
        //1.查询用户信息
        UserInfo userInfo = userInfoService.find(userId);
        if(null == userInfo) return null;
        //2.查询地址信息
        ShopUserAddress address = new ShopUserAddress();
        //如果地址是-1,表示用户没有添加地址
        if(!"-1".equals(addressId)){
            address = shopUserAddressService.find(addressId);
            if(null == address) return null;
        }
        //3.查询购物车信息
        String[] ids = cartIds.split(",");
        List<ShopCart> cartList = new ArrayList<>();
        for(String str:ids){
            ShopCart cart = shopCartService.find(str);
            if(null != cart && userInfo.getUserId().equals(cart.getUserId())){
                goodsTotalPrice = cart.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getGoodsNum())).add(goodsTotalPrice);
                orderTotalPrice = cart.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getGoodsNum())).add(orderTotalPrice);
                cartList.add(cart);
            }
        }
        //4.计算订单金额
        if(cartList.size() == 0) return null;
        vo.setAddress(address);
        vo.setCartList(cartList);
        vo.setGoodsTotalPrice(NumberTool.formatToNumber(goodsTotalPrice));
        vo.setOrderFreightPrice(NumberTool.formatToNumber(orderFreightPrice));
        vo.setOrderTotalPrice(NumberTool.formatToNumber(orderTotalPrice));
        return vo;
    }

    /**
     * 加入购物车
     * @param userId    用户ID
     * @param goodsId   商品ID
     * @param goodsNum  商品数量
     */
    public ShopCart addCart(String userId, String goodsId, String goodsNum) {
        //1.查询购物车有无此商品
        ShopCart findCart = new ShopCart();
        findCart.setUserId(userId);
        findCart.setGoodsId(goodsId);
        List<ShopCart> list = shopCartService.findList(findCart);
        if(null != list && list.size() > 0){
            ShopCart cart = list.get(0);
            if(cart.getGoodsNum() != Integer.valueOf(goodsNum)){
                cart.setGoodsNum(Integer.valueOf(goodsNum));
                shopCartService.update(cart);
            }
            return cart;
        }
        //2.查询用户信息
        UserInfo userInfo = userInfoService.find(userId);
        if(null == userInfo) return null;
        //3.查询商品信息
        ShopGoods goods = shopGoodsService.find(goodsId);
        if(null == goods) return null;
        //4.添加购物车
        ShopCart cart = new ShopCart();
        cart.setUserId(userInfo.getUserId());
        cart.setGoodsId(goods.getGoodsId());
        cart.setGoodsName(goods.getGoodsName());
        cart.setGoodsImage(goods.getGoodsImage());
        cart.setGoodsPrice(goods.getGoodsPrice());
        cart.setGoodsNum(Integer.valueOf(goodsNum));
        shopCartService.save(cart);
        return cart;
    }

    /**
     * 删除购物车
     * @param cartIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void delCart(String cartIds) {
        String[] strs = cartIds.split(",");
        for(String cartId:strs){
            shopCartService.delete(cartId);
        }
    }
}

